import axios from 'axios';

const headers = {
  'X-REQUESTED-WITH': 'xmlhttprequest'
};
const instance = axios.create({
  baseURL: '',
  method: 'post',
  timeout: 5000
});
instance.interceptors.response.use(function (response) {
  if (response.data.status === 0 || response.data.code === 0) {
    return response.data;
  }
  if (response.data.status === 401) {
    location.reload();
  }
  $tools.notification.error({
    message: '错误',
    description: response.data.msg || response.data.message
  });
  return Promise.reject(response.data);
}, function (error) {
  $tools.notification.error({
    message: '错误',
    description: '请求失败'
  });
  return Promise.reject(error);
});

window.$request = function (url, data, options) {
  return instance(Object.assign({
    method: 'post',
    url: url,
    data: data
  }, options))
}

window.loadPageSchema = function (url) {
  return new Promise((resolve, reject) => {
    axios.post(url, {}, {
      headers: headers
    }).then(res => {
      const {data, status} = res;
      const fn = new Function(`return ${data}`);
      resolve(fn())
    }).catch(err => {
      console.log(err);
      if (err.response) {
        if (err.response.status === 401) {
          location.reload();
        }
        if (err.response.status === 403) {
          var error = new Error('无权限访问');
          error.name = '无权限';
          reject(error);
        }
      }
      reject(err)
    })
  })
}
